package com.pw.study.flink.window;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.Arrays;

public class CountWindow {
    public static void main(String[] args) {
        dealCount();
    }

    private static void dealCount() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        SingleOutputStreamOperator<Tuple2<String, Long>> stream = env.socketTextStream("hadoop111", 9999).flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                Arrays.stream(value.split(" ")).forEach(word -> out.collect(Tuple2.of(word, 1L)));
            }
        });
        stream.keyBy(t -> t.f0).countWindow(3, 1).process(new ProcessWindowFunction<Tuple2<String, Long>, String, String, GlobalWindow>() {
            @Override
            public void process(String key, Context ctx, Iterable<Tuple2<String, Long>> elements, Collector<String> out) throws Exception {
                int count = 0;
                for (Tuple2<String, Long> elem : elements) {
                    count++;
                }
                out.collect("key: " + key + " ,个数 " + count);
            }
        }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
